<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\CreateException;
use App\Exceptions\DeleteException;
use App\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @property Member model
 */
class MemberController extends Controller
{
    public function __construct(Member $model)
    {
        $this->model = $model;
    }

    /**
     * Display a listing of the resource.
     *
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($id,Request $request)
    {
        $page  = $request->get('page',1);
        $size  = $request->get('size',10);
        $list = $this->model->where('craftmans',$id)->limit($size)->offset(($page-1)*$size)->get();
        $count = $this->model->where('craftmans',$id)->count();
        return $this->page($list,$count);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws CreateException
     */
    public function store(Request $request)
    {
        $member = $request->only(['city','hope_city','name','card','phone','headman_images','craftmans']);
        if ($res = (new \App\Logic\Craftsman())->addMember($member))
            return $this->success();
        throw new CreateException();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($id)
    {
        if ($this->model->whereId($id)->delete())
            return $this->success();
        throw new DeleteException();
    }
}
